<template>
  <div>
    <!-- header -->
    <div class="hero-header">
      <div class="header-content" style="margin-left: 50px; display: flex; align-items: center;">
        <span class="header-logo" style="width: 100px; height: 100px;">
          <img style="display: inline-block; width: 100px; height: 100px;" src="/src/pages/index/static/logo.png" alt="">
        </span>
        <span class="hear-text" style="width: 300px;">
          <div style=" margin-top: 10px;display: inline-block; color: #215eba; font-size: 16px; font-weight: 700; ">
            区块链安全保障技术政务平台
          </div>
          <div class="hearderPitem" style="width: 500px; color: #3172d4; font-size: 28px; font-weight: 800;">
            社会保障助老多功能平台
          </div>
        </span>
        <img style="margin-left: 7%; height: 40px; zoom: 2;" src="/src/pages/index/static/flag5.png" alt="">
        <!-- <img style="margin-left: 7%; height: 40px;" src="/src/pages/index/static/flag.png" alt="">
        <img style="margin-left: 5%; height: 40px;" src="/src/pages/index/static/flag2.png" alt=""> -->
        <!-- <div class="header-right" style="float: right;">123456</div> -->
        <div class="button" @click="router.back()" style="background: #fff; border: 1px solid #5771d1; color: #5771d1; position: absolute; right: 20px; top: 28px; z-index: 999; padding: 8px 16px; cursor: pointer; border-radius: 4px; transition: background-color 0.3s, color 0.3s;">
          返回
        </div>
      </div>
    </div>

    <!-- content -->
    <el-row class="login">
      <video
        autoplay
        loop
        class="video-bg"
        :style="videoStyle"
        muted="muted"
        poster=""
        width="100%"
      >
        <source src="../User/static/oldman2.mp4" type="video/mp4" />
      </video>
      <!-- 表单 -->
      <div
        class="login-form"
        style="
          padding: 40px;
          margin-top: 20%;
          border-radius: 2px;
          width: 30%;
          opacity: 0.95;
          background-color: rgba(255, 255, 255, 0.8);
        "
      >
        <h1 class="login-title">助老多功能管理平台</h1>
        <h3 class="login-subtitle">注册界面</h3>

        <el-form label-width="150px" :model="formData" :rules="rules">
          <el-form-item label="用户类型" prop="user_type" label-position="left">
            <el-select @change="selectForm" style="width: 300px" v-model="formData.user_type" placeholder="请选择用户类型">
              <el-option label="员工" value="1"></el-option>
              <el-option label="工作单位" value="2"></el-option>
              <el-option label="社保局" value="3"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="姓名：" label-position="left" v-show="confirmEmployee">
            <el-input style="width: 300px" v-model="formData.name" placeholder="请输入你的真实姓名" />
          </el-form-item>
          <el-form-item label="年龄：" label-position="left" v-show="confirmEmployee">
            <el-input style="width: 300px" v-model="formData.age" placeholder="请输入你的真实年龄" />
          </el-form-item>
          <el-form-item label="性别" label-position="left" v-show="confirmEmployee">
            <el-radio-group v-model="formData.sex">
              <el-radio label="男" value="1"></el-radio>
              <el-radio label="女" value="2"></el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="手机号码" prop="phone" label-position="left" v-show="confirmEmployee">
            <el-input style="width: 300px" v-model.number="formData.phone" placeholder="请输入你的手机号码" />
          </el-form-item>
          <el-form-item label="身份证号码" prop="idNumber" label-position="left" v-show="confirmEmployee">
            <el-input style="width: 300px" v-model="formData.idNumber" placeholder="请输入你的身份证号码" />
          </el-form-item>
          <el-form-item label="缴费日期" prop="date" label-position="left" v-show="confirmEmployee">
            <!-- <el-input style="width: 300px" v-model="formData.phone" placeholder="请输入你的缴费日期" /> -->
            <el-date-picker v-model="formData.date" type="date" :size="size" placeholder="选择日期"/>
          </el-form-item>
          <el-form-item label="雇主名字" prop="employerName" label-position="left" v-show="confirmEmployee">
            <el-input style="width: 300px" v-model="formData.employerName" placeholder="请输入你的雇主名字" />
          </el-form-item>
          <el-form-item label="公司名字" prop="employerName" label-position="left" v-show="confirmEmployer">
            <el-input style="width: 300px" v-model="formData.employerName" placeholder="请输入你的公司名字" />
          </el-form-item>
          <el-form-item label="工资" prop="salary" label-position="left" v-show="confirmEmployee">
            <el-input style="width: 300px" v-model.number="formData.salary" placeholder="请输入你的工资" />
          </el-form-item>
          <!-- 雇主item -->
          <el-form-item label="工作地址" prop="employerAddress" label-position="left" v-show="false">
            <el-input style="width: 300px" v-model = "formData.employerAddress" placeholder="请输入你的雇主地址" />
          </el-form-item>
          <!-- 社保局item -->
          <el-form-item label="社保局名字" prop="bureauName" label-position="left" v-show="confirmBureau">
            <el-input style="width: 300px"  v-model="formData.bureauName" placeholder="请输入你的社保局名字" />
          </el-form-item>
          <el-form-item label="社保局地址" prop="bureauAddress" label-position="left" v-show="false">
            <el-input style="width: 300px" v-model="formData.bureauAddress" placeholder="请输入你的社保局地址" />
          </el-form-item>
          
          <div class="login-buttons">
            <el-button type="primary" @click="login">返回</el-button>
            <el-button type="primary" @click="register">注册</el-button>
            <el-button
              type="primary"
              @click="resetForm"
              style="margin-left: 1em"
            >重置</el-button>
          </div>
        </el-form>
      </div>
    </el-row>
    <!-- 弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      title="账号密码信息"
      width="500"
      :before-close="handleClose"
    >
    <div>你的账号地址是：{{ employeeAddress }}</div>
    <div>你的密钥是：{{ signSecurity }}</div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="closeDialog">
            已记住
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import myAxios from '../../plugins/myAxios.js';
import { useCookies } from 'vue3-cookies';
import { ElMessageBox } from 'element-plus';
import { ElNotification } from 'element-plus'

const { cookies } = useCookies();

const formData = ref({
  name: '',
  age: null,
  sex: '',
  user_type: '',
  phone: '',
  idNumber: '',
  salary: null,
  employerName: '',
  employerAddress: '',
  bureauName: '',
  bureauAddress: '',
  date: ''
});
// 密钥
const signSecurity = ref({});
// 地址
const employeeAddress = ref({});
// 弹窗控制
const dialogVisible = ref(false);

const confirmEmployee = ref(false)
const confirmEmployer = ref(false)
const confirmBureau = ref(false)
const rules = {
  name: [
    { required: true, message: '请输入你的真实姓名', trigger: 'blur' },
    { min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' },
  ],
  age: [
    { required: true, message: '年龄不能为空' },
    { type: 'number', message: '年龄必须为数字值' },
    { trigger: 'blur' }, // 添加自定义年龄范围验证器
  ],
  sex: [{ required: true, message: '请选择性别', trigger: 'change' }],
  user_type: [{ required: true, message: '请选择用户类型', trigger: 'change' }],
  phone: [
    { required: true, message: '电话号码不能为空', trigger: 'blur' },
    { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的电话号码', trigger: 'blur' },
  ],
  idNumber: [
    { required: true, message: '身份证号不能为空', trigger: 'blur' },
    {
      pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
      message: '请输入正确的身份证号',
      trigger: 'blur',
    },
  ],
  date: [
    { required: true, message: '请选择缴费日期', trigger: 'blur' },
  ],
  employerName: [
    { required: true, message: '如果没有则填无', trigger: 'blur' },
  ],
  salary: [
    { required: true, message: '薪水不能为空', trigger: 'blur' },
    { type: 'number', message: '薪水必须为数字值', trigger: 'blur' },
  ],
  employerAddress: [
    { required: true, message: '请输入雇主地址', trigger: 'blur' },
  ],
  bureauName: [
    { required: true, message: '请输入社保局名字', trigger: 'blur' },
  ],
  bureauAddress: [
    { required: true, message: '请输入社保局地址', trigger: 'blur' },
  ],
};

const router = useRouter();

// 方法
const login = () => {
  router.push('/user/login');
};
// 校验表单数据
const validateForm = () => {
  return new Promise((resolve, reject) => {
    const validateResult = (rule, value, callback) => {
      if (value === '') {
        callback(new Error(rule.message));
      } else {
        callback();
      }
    };
    for (const key in rules) {
      rules[key].forEach((rule) => {
        validateResult(rule, formData.value[key], () => {});
      });
    }
    resolve();
  });
}
//注册功能
const register = async () => {
    await validateForm(); // 校验表单数据
    // 参保人注册逻辑
    // 员工注册逻辑
    if(confirmEmployee.value) {
      // 构造要发送的JSON对象 // todo 还有点问题
      if(formData.value.idNumber === '000000000000000000'){
        ElNotification({
          title: '失败',
          message: `注册失败,身份证有误`,
          type: 'error',
        })
        return;
      }
      if(formData.value.salary === 0){
        ElNotification({
          title: '失败',
          message: `注册失败,工资不能为零`,
          type: 'error',
        })
        return;
      }
      const personBo = {
      name: formData.value.name,
      age: formData.value.age, // 年龄
      sex: formData.value.sex,
      userType: formData.value.user_type,
      phone: formData.value.phone,
      idNumber: formData.value.idNumber, // 身份证号
      salary: formData.value.salary, // 薪水
      employer: formData.value.employerName, //雇主名字
      startDate: formData.value.date ? formData.value.date.getTime() : '',
      };
          // 发送POST请求到后端注册接口
      try {
        const response = await myAxios.post('/user/addPerson', personBo);
        if (response.data.code == 200) {
          // 注册成功，可以展示成功提示，然后跳转到登录页或其他页面
          const jsonData = response.data.data
          if(jsonData !== 'ok'){
            const parsedData = JSON.parse(jsonData)
            signSecurity.value = parsedData.signSecurity
            employeeAddress.value = parsedData.employeeAddress
            dialogVisible.value = true
            console.log(dialogVisible.value)
            ElNotification({
              title: '成功',
              message: '注册成功',
              type: 'success',
            })
          }
          if(jsonData == 'ok'){
            console.log('ok')
            ElNotification({
              title: '成功',
              message: '注册成功',
              type: 'success',
            })
          }
          // 后端会传什么数据 接受一下 比如存个对象？

        } else {
          // 注册失败，展示错误信息
          ElNotification({
            title: '失败',
            message: `注册失败,${response.data.msg}`,
            type: 'error',
          })
        }
      }catch (e) {
        ElNotification({
          title: '失败',
          message: `注册失败`,
          type: 'error',
        })
      }

    }

    // 雇主注册逻辑 
    if(confirmEmployer.value) {
          const InsuranceAccountBo = {
          // sponsorAddress: formData.value.employerAddress,
          sponsorName: formData.value.employerName,
        }
        try {
          const response = await myAxios.post('/sponsor/addSponsor', InsuranceAccountBo);
          if (response.data.code === 200) {
            // 注册成功，可以展示成功提示，然后跳转到登录页或其他页面
            const sponsorAddress = response.data.data.sponsorAddress
            const signSecurity2 = response.data.data.signSecurity
            employeeAddress.value = sponsorAddress
            signSecurity.value = signSecurity2
            dialogVisible.value = true
            console.log(dialogVisible.value)
          }else{
            ElNotification({
              title: '失败',
              message: `注册失败,${response.data.msg}`,
              type: 'error',
            })
          }
        } catch (e) {
            ElNotification({
              title: '失败',
              message: `注册失败`,
              type: 'error',
            })
        }

          
          
    }
  
    // 社保局注册逻辑
    if(confirmBureau.value) {
          const SocialSecurityBureauBo = {
          bureauCity: formData.value.bureauName,
          // bureauAddress: formData.value.bureauAddress,
        }
        try {
          const response = await myAxios.post('/social/addBureaus', SocialSecurityBureauBo);
          if (response.data.code === 200) {
            // 注册成功，保存密钥和账号
            // 把json数据转化
            ElNotification({
              title: '成功',
              message: '注册成功',
              type: 'success',
            })
            const bureauAddress = response.data.data.bureauAddress
            const signSecurity2 = response.data.data.signSecurity
            console.log(response.data.data)
            signSecurity.value = signSecurity2
            employeeAddress.value =  bureauAddress
            dialogVisible.value = true
          } else {
            ElNotification({
              title: '失败',
              message: `注册失败,${response.data.msg}`,
              type: 'error',
            })
          }
        } catch (e) {
          ElNotification({
            title: '失败',
            message: `注册失败`,
            type: 'error',
          })
        }

    }
}

const selectForm = () => {
  console.log(formData.value.user_type);
  if (formData.value.user_type === '1'){
    confirmBureau.value = false;
    confirmEmployer.value = false;
    confirmEmployee.value = true;
    console.log(confirmEmployee)
  }
  if (formData.value.user_type === '2'){
    confirmBureau.value = false;
    confirmEmployee.value = false;
    confirmEmployer.value = true;
  }
  if (formData.value.user_type === '3'){
    confirmEmployer.value = false;
    confirmEmployee.value = false;
    confirmBureau.value = true;
    console.log(confirmBureau)
  }
}

const resetForm = () => {
  formData.value = {
    name: '',
    age: null,
    sex: '',
    user_type: '',
    phone: '',
    idNumber: '',
    salary: null,
  };
};
//弹窗关闭处理
const handleClose = () => {
  ElMessageBox.confirm('是否要进行关闭?')
    .then(() => {
      router.push('/user/login');
      
    })
    .catch(() => {
      // catch error
    })
}
// 弹窗按钮关闭逻辑
const closeDialog = () => {
  dialogVisible.value = false
  router.push('/user/login');
}
// 视频处理
const handleWindowResize = () => {
  const windowWidth = document.body.clientWidth;
  const windowHeight = document.body.clientHeight;
  const windowAspectRatio = windowHeight / windowWidth;
  let videoWidth;
  let videoHeight;

  if (windowAspectRatio < 0.5625) {
    videoWidth = windowWidth;
    videoHeight = videoWidth * 0.5625;
    this.videoStyle = {
      height: windowWidth * 0.5625 + 'px',
      width: windowWidth + 'px',
    };
  } else {
    videoHeight = windowHeight;
    videoWidth = videoHeight / 0.5625;
    this.videoStyle = {
      height: windowHeight + 'px',
      width: windowHeight / 0.5625 + 'px',
    };
  }
};

const onMounted = () => {
  handleWindowResize();
  window.addEventListener('resize', handleWindowResize);
  this.$once('hook:beforeDestroy', () => {
    window.removeEventListener('resize', handleWindowResize);
  });
};
</script>

<style scoped>
  /**按钮 */
  .button:hover {
    background-color: #5771d1;
    color: #fff;
  }

  /* 初始 */
  .el-dropdown-link {
    cursor: pointer;
    color: #409eff;
  }

  .el-icon-arrow-down {
    font-size: 12px;
  }

  .login {
    position: relative;
    height: 100%;
    background: #fff url('') no-repeat fixed center center / cover;
  }

  .video-bg {
    z-index: 0;
    position: absolute;
    height: 100vh;
    left: 0;
    right: 0;
  }

  .login-form {
    z-index: 1;
    position: absolute;
    margin-top: 200px;
    left: 70%;
    transform: translate(-50%, -50%);
    opacity: 0.8;
  }

  .login-title {
    text-align: center;
    font-size: 2em;
    margin-bottom: 0.5em;
    color: #3172d4;
  }

  .login-subtitle {
    text-align: center;
    font-size: 1.2em;
    color: #666;
    margin-bottom: 2em;
  }

  .login-buttons {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 2em;
  }

  .login-buttons .el-button {
    min-width: 100px;
  }

  .signup {
    position: relative;
    left: 12%;
    border: 0px;
  }
</style>